package com._21cn.cms.resource.utils.upload;

import com._21cn.cms.resource.utils.UploadHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * UploadHandler的适配器，已对接口中的方法进行空实现
 * 
 * @author chenjh
 */
public class UploadHandlerAdapter implements UploadHandler {
	private static final Logger log = LoggerFactory.getLogger(UploadHandlerAdapter.class);

	@Override
	public boolean beforeUpload(HttpServletRequest request, HttpServletResponse response ) {
		return true;
	}

	@Override
	public Map<UploadHelper.UploadResultType, List<Object>> afterUpload(Map<UploadHelper.UploadResultType,
			Map<String, File>> map, HttpServletRequest request, HttpServletResponse response ) {
		return null;
	}

	@Override
	public Map<UploadHelper.UploadResultType, Map<String, File>> process(HttpServletRequest request, HttpServletResponse response ) {
		Map<UploadHelper.UploadResultType, Map<String, File>> resultMap = new HashMap<UploadHelper.UploadResultType, Map<String, File>>();
		Map<String, File> success = new HashMap<String, File>();
		Map<String, File> fail = new HashMap<String, File>();
		resultMap.put( UploadHelper.UploadResultType.SUCCESS, success );
		resultMap.put( UploadHelper.UploadResultType.FAIL, fail );
		// 获取parts
		Collection<Part> parts = null;
		try {
			parts = request.getParts();
		} catch( IOException e ) {
			log.error( e.getMessage() );
		} catch( ServletException e ) {
			log.error( e.getMessage() );
		}
		// 从请求中提取文件
		for( Part part : parts ) {
			String fileName = UploadHelper.getFileName( part );
			// 处理值为空的表单项
			if( StringUtils.isEmpty( fileName ) )
				continue;
			// 把文件暂存到临时目录，临时文件名利用uuid生成 ，注意要处理Resin服务器保存路径的兼容问题
			StringBuilder tempPath = new StringBuilder( "upload_" )
					.append( UUID.randomUUID().toString() )
					.append( UploadHelper.getFileSuffix(part) );
			File file = null;
			try {
				if( UploadHelper.isResin() ) {
					part.write( tempPath.toString() );
					file = new File( tempPath.insert( 0, "/tmp/" ).toString() );
				} else {
					tempPath = tempPath.insert( 0, "/tmp/" );
					part.write( tempPath.toString() );
					file = new File( tempPath.toString() );
				}
			} catch( IOException e ) {
				log.error( e.getMessage() );
				fail.put( fileName, file );
				continue;
			}
			success.put( fileName, file );
		}

		return resultMap;
	}
}